// stores/calculatorStore.ts
import { defineStore } from 'pinia'

export const useCalculatorStore = defineStore('calculator', {
    // 状态：存储计算器相关数据
    state: () => ({
        num1: 0 as number,
        num2: 0 as number,
        operator: '+' as '+' | '-' | '*' | '/', // 限制运算符只能是指定类型
        result: 0 as number
    }),

    // 行为：处理状态更新和计算逻辑
    actions: {
        // 设置第一个数字
        setNum1(value: number) {
            this.num1 = value
        },

        // 设置第二个数字
        setNum2(value: number) {
            this.num2 = value
        },

        // 设置运算符
        setOperator(op: '+' | '-' | '*' | '/') {
            this.operator = op
        },

        // 执行计算逻辑
        calculate() {
            switch (this.operator) {
                case '+':
                    this.result = this.num1 + this.num2
                    break
                case '-':
                    this.result = this.num1 - this.num2
                    break
                case '*':
                    this.result = this.num1 * this.num2
                    break
                case '/':
                    if (this.num2 !== 0) {
                        this.result = this.num1 / this.num2
                    } else {
                        this.result = 0 // 除数为0时重置结果
                        alert('错误：除数不能为0')
                    }
                    break
            }
        },

        // 重置计算器状态
        reset() {
            this.num1 = 0
            this.num2 = 0
            this.operator = '+'
            this.result = 0
        }
    }
})